<script setup>
import {onMounted, ref} from 'vue';
import * as home from '@/api/home/index'
import {message} from "ant-design-vue";
import {QuestionCircleOutlined} from '@ant-design/icons-vue';

// 定义 emits
const emit = defineEmits(['close']);

const groups = ref([]);
const newGroupName = ref('');
const currentGroupName = ref('');
const currentGroupId = ref(null);
const isEditing = ref(false);
const isAdding = ref(false);

// 获取分组数据的异步函数
const fetchGroups = async () => {
  try {
    const response = await home.getGroup();
    groups.value = response.data;
  } catch (error) {
    console.error('获取分组失败', error);
  }
};

// 显示新增分组的模态框
const showAddModal = () => {
  newGroupName.value = '';
  isAdding.value = true;
};

// 显示编辑分组的模态框
const showEditModal = (group) => {
  currentGroupId.value = group.id;
  currentGroupName.value = group.name;
  isEditing.value = true;
};

// 处理新增分组
const handleAdd = async () => {
  try {
    await home.addGroup({name: newGroupName.value});
    isAdding.value = false;
    fetchGroups();  // 刷新分组列表
  } catch (error) {
    message.error('新增分组失败', error);
  }
};

// 处理编辑分组
const handleEdit = async () => {
  try {
    const obj = {
      id: currentGroupId.value,
      name: currentGroupName.value
    }
    await home.editGroup(obj);
    isEditing.value = false;
    fetchGroups();  // 刷新分组列表
  } catch (error) {
    message.error('编辑分组失败', error);
  }
};

// 取消操作
const handleCancel = () => {
  emit('close');  // 触发关闭事件
};

// 关闭编辑模态框
const closeEditModal = () => {
  isEditing.value = false;
};

// 关闭新增模态框
const closeAddModal = () => {
  isAdding.value = false;
};

// 删除分组的函数
const deleteGroup = async (id) => {
  try {
    await home.delGroup(id);
    fetchGroups();  // 刷新分组列表
  } catch (error) {
    message.error('删除分组失败', error);
  }
};

// 组件挂载时获取分组数据
onMounted(() => {
  fetchGroups();
});
</script>

<template>
  <a-flex vertical gap="middle">
    <a-button type="primary" @click="showAddModal" style="width:fit-content;">新增分组</a-button>

    <a-flex gap="middle" align="center" justify="space-between" v-for="group in groups" :key="group.id">
      <a-typography-text strong>{{ group.name }}</a-typography-text>
      <a-flex gap="small" horizontal>
        <a-button type="primary" @click="showEditModal(group)">编辑</a-button>
        <a-popconfirm @confirm="deleteGroup(group.id)" okText="确定" cancelText="取消" title="关联的数据也会一起删除！">
          <template #icon>
            <question-circle-outlined style="color: red"/>
          </template>
          <a-button type="primary" danger>删除</a-button>
        </a-popconfirm>
      </a-flex>
    </a-flex>
  </a-flex>

  <a-modal :open="isEditing" title="编辑分组" @cancel="closeEditModal" @ok="handleEdit">
    <a-input placeholder="请输入分组名称" v-model:value="currentGroupName"/>
  </a-modal>

  <a-modal :open="isAdding" title="新增分组" @cancel="closeAddModal" @ok="handleAdd">
    <a-input placeholder="请输入分组名称" v-model:value="newGroupName"/>
  </a-modal>
</template>

<style scoped>

</style>